@echo off
chcp 65001 > nul  
setlocal enabledelayedexpansion

:: ==================== 配置参数 ====================
set MYSQL_PATH="C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe"
set MYSQL_USER="root"
set MYSQL_PASSWORD="XINGshan@123"
set DATABASES="lx_sys"  
set BACKUP_DIR=".\\lx_bak\\"
set LOG_FILE=%BACKUP_DIR%\backup_log.txt
:: ==================================================
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set "datetime=%%I"

:: 提取日期和时间部分（格式：YYYYMMDD_HHMMSS）
set "DATE_STR=!datetime:~0,8!"  
set "TIME_STR=!datetime:~8,6!"  
set "TIMESTAMP=!DATE_STR!_!TIME_STR!"  


if not exist "%BACKUP_DIR%" mkdir "%BACKUP_DIR%"

echo [%date% %time%] 开始备份... >> %LOG_FILE%
%MYSQL_PATH% --user=%MYSQL_USER% --password=%MYSQL_PASSWORD% --databases %DATABASES% --single-transaction --quick --add-drop-database --default-character-set=utf8mb4 > "%BACKUP_DIR%\full_backup_%TIMESTAMP%.sql" 2>> %LOG_FILE%
@REM %MYSQL_PATH% --user=%MYSQL_USER% --password=%MYSQL_PASSWORD% --databases %DATABASES% --create-db --single-transaction --quick --add-drop-database --default-character-set=utf8mb4 > "%BACKUP_DIR%\full_backup_%TIMESTAMP%.sql" 2>> %LOG_FILE%
if %errorlevel% equ 0 (
    echo [%date% %time%] 备份成功！文件路径：%BACKUP_DIR%\full_backup_%TIMESTAMP%.sql >> %LOG_FILE%
) else (
    echo [%date% %time%] 备份失败！错误信息见日志：%LOG_FILE% >> %LOG_FILE%
    exit /b 1
)

echo [%date% %time%] 清理 7 天前的旧备份... >> %LOG_FILE%
forfiles /p "%BACKUP_DIR%" /m "full_backup_*.sql" /d -7 /c "cmd /c del @path"
echo [%date% %time%] 清理完成 >> %LOG_FILE%

endlocal